﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace DelegateTest
{
    internal delegate void FeedBack(Int32 value);
    class DelTest1
    {

        public static void AllFunction()
        {
            StaticDelegateDemo();
            InstanceDelegateDemo();
            ChainDelegateDemo1(new DelTest1());
            ChainDelegateDemo2(new DelTest1());
        }

        private static void StaticDelegateDemo()
        {
            Console.WriteLine("StaticDelegateDemo");
            Counter(1, 3, null);
            Counter(1, 3, new FeedBack(DelTest1.FeedBackToConsole));
            Counter(1, 3, new FeedBack(FeedbackToMsgBox));
            Console.WriteLine();
        }

        private static void InstanceDelegateDemo()
        {
            Console.WriteLine("InstanceDelegateDemo");
            DelTest1 dt = new DelTest1();
            Counter(1, 3, new FeedBack(dt.FeedbackToFile));
        }

        private static void ChainDelegateDemo1(DelTest1 dt)
        {
            Console.WriteLine("ChainDelegateDemo1");
            FeedBack fb1 = new FeedBack(FeedBackToConsole);
            FeedBack fb2 = new FeedBack(FeedbackToMsgBox);
            FeedBack fb3 = new FeedBack(dt.FeedbackToFile);

            FeedBack fbChain = null;
            fbChain = (FeedBack)Delegate.Combine(fbChain, fb1);
            fbChain = (FeedBack)Delegate.Combine(fbChain, fb2);
            fbChain = (FeedBack)Delegate.Combine(fbChain, fb3);
            Counter(1, 3, fbChain);
            Console.WriteLine();
            fbChain = (FeedBack)Delegate.Remove(fbChain, new FeedBack(FeedbackToMsgBox));
            Counter(1, 3, fbChain);
        }

        private static void ChainDelegateDemo2(DelTest1 dt)
        {

        }

        private static void Counter(Int32 from, Int32 to, FeedBack fb)
        {
            for (Int32 val = from; val <= to; val++ )
            {
                if (fb != null)
                {
                    fb(val);
                }
            }
        }

        private static void FeedBackToConsole(Int32 value)
        {
            Console.WriteLine("Item=" + value);
        }

        private static void FeedbackToMsgBox(Int32 value)
        {
            MessageBox.Show("Item=" + value);
        }

        private void FeedbackToFile(Int32 value)
        {
            StreamWriter sw = new StreamWriter("Status",true);
            sw.WriteLine("Item=" + value);
            sw.Close();
        }
    }
}
